package com.he.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.he.entity.ResultData;
import com.he.entity.User;
import com.he.service.IUserService;
import com.he.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public ResultData<Integer> register(User user){
        try {
            System.out.println("注册信息："+user);
            boolean save = userService.save(user);
            return new ResultData<Integer>().setData(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultData<Integer>().setCode(ResultData.Code.ERROR).setMsg("用户名已注册！！！");
    }


    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public ResultData<String> login (String username,String password,String devId){

        System.out.println("登录设备号；" + devId);

        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq("username",username)
                .eq("password",password);
        User user = userService.getOne(wrapper);
        if(user != null){
            //登录成功
            String jwtToken = JwtUtil.createJwtToken(user,devId);
            //System.out.println("登录成功："+jwtToken);
            return new ResultData<String>().setData(jwtToken);
        }
        //登录失败
        return new ResultData<String>().setCode(ResultData.Code.ERROR).setData(null).setMsg("账号或密码错误!");
    }


}
